package org.xdj.blue.java.io.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * socket客户端线程
 * @author 91power—xdj
 *
 */
public class ClientSocket implements Runnable {

	public static Logger logger = LoggerFactory.getLogger(ClientSocket.class);
	private int port;
	private String url;
	private Socket socket;
	private BufferedReader reader;
	private PrintWriter writer;
	private StringBuilder response = new StringBuilder();
	private String request;

	public ClientSocket(String url, int port) {
		this.url = url;
		this.port = port;
	}

	public void run() {
		String resp = "";
		try {
			//创建连接
			socket = new Socket(url, port);

			writer = new PrintWriter(socket.getOutputStream(), true);
			//好吧，这地方被深深埋进坑了，reader.readLine()一定要读到"\r",不然阻塞。。。
			request = "1\r2\r3\rover\r";
			writer.write(request);
			// 不主动flush会持续阻塞，坑爹，创建PrintWriter的时候明明设置自动flush了，不起效果
			writer.flush();
			reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));

			while (true) {
				logger.debug("--client-read--");
				resp = reader.readLine();
				// 以"over"作为结束标识符
				if (null == resp || resp.equals("over")) {
					break;
				}
				response.append(resp);
				logger.debug("resp:" + resp);
			}
		} catch (Exception e) {
			logger.error("---数据交互异常 ---");
			e.printStackTrace();
		}
		logger.debug("response：" + response.toString());
		try {
			if (reader != null) {
				reader.close();
			}
			if (writer != null) {
				writer.close();
			}
			if (socket != null) {
				socket.close();
			}
		} catch (Exception e) {
			logger.error("---client关闭异常---");
		}

	}

}
